Home:ALL Converter>How to pass warnings outside of functions as exceptions, but without program interruption

How to pass warnings outside of functions as exceptions, but without program interruption

Ask Time:2020-02-24T00:43:41         Author:Alex Gh

Json Formatter

I have a program that implements a model and a view.

I want the model to do some processing and return a warning to the view if something didn't go right.

Now, I want the warning to be passed around as sort of an exception, so if I have a GUI as a view, I can easily create a Message Box or something similar to that to show the warning, but without interrupting program flow.

Is there any way I can achieve this?

Note: I am aware of the warnings module in Python, but I do not know if I can pass those warnings as exceptions that don't interrupt program flow.

Relevant code:

class Model():

   def __init__(self):
      try:
         with open(some_file) as file:
            self.file = file.readlines()
      except FileNotFoundError:
         # I don't want the Model to print the message here
         # print("Warning: File not found, continuing with defaults")
         # I want a warning to be passed up to the view
         self.file = 'some piece of data'
         raise FileNotFoundError(error_msg)
class View():

   def __init__(self):
      try:
         self.model = Model()
      except FileNotFoundError:
         # I want to catch the warning here and display it
         # but if I catch an exception here, Python will complain that
         # self.model was not initialized correctly when I use it later

Thanks

Author:Alex Gh,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60364489/how-to-pass-warnings-outside-of-functions-as-exceptions-but-without-program-int
yy